package com.zkc.bootnew.webserviceimpl;

import com.zkc.bootnew.webservice.RpcTokenService;
import com.zkc.bootnew.webservice.webuserservice;
import com.zkc.springbootnew.bean.Contact_user;
import com.zkc.springbootnew.service.userservice;
import com.zkc.springbootnew.utils.EmptyUtils;
import com.zkc.springbootnew.utils.ErrorCode;
import com.zkc.springbootnew.utils.GotripException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
@Service
public class webuserserviceimpl implements webuserservice {

    @Resource
    userservice userservice;

    @Resource
    private RpcTokenService rpcTokenService;


    @Override
    public List<Contact_user> userAll() throws Exception {
        List<Contact_user> lists= userservice.userAll();
        return lists;
    }

    @Override
    public Contact_user usersingle(Integer id) throws Exception {
        return userservice.usersingle(id);
    }

    @Override
    public Integer usermodify(Contact_user contact_user) throws Exception {
        return userservice.usermodify(contact_user);
    }

    @Override
    public Integer userdelete(Integer xid) throws Exception {
        return userservice.userdelete(xid);
    }

    @Override
    public Integer UserAdd(Contact_user contact_user) throws Exception {
        return userservice.UserAdd(contact_user);
    }

    @Override
    public Contact_user UserLogin(String ContactAlias) throws Exception {
        if(EmptyUtils.isEmpty(ContactAlias)){
            throw new GotripException("用户名ContactAlias不能为空！", ErrorCode.AUTH_PARAMETER_ERROR);
        }
        return userservice.UserLogin(ContactAlias);
    }

    @Override
    public String doLogin(Contact_user user, String password, String userAgent) throws Exception {
         //判断用户是否存在
        if(EmptyUtils.isEmpty(user)){
            throw new GotripException("用户不存在",ErrorCode.AUTH_AUTHENTICATION_FAILED);
        }
        //密码判断
        if(!password.equals(user.getPassword())){
            throw new GotripException("密码错误",ErrorCode.AUTH_ACTIVATE_FAILED);
        }
        //将密码重置
        user.setPassword(null);
        //生成token
        String token= rpcTokenService.generateToken(user,userAgent);

        //保存token
        rpcTokenService.saveToken(token,user);

        return token;
    }
}
